// pages/departList/departList.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';
import { relativeTimeThreshold } from '../../libs/moment.min.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //当前登录用户
    user:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,  
    //客户选择框
    showMember:false,
    //客户选择数据
    memberList:[],
    //选择的客户信息
    member:null,
    //用户权限
    authority:null,
    //搜索客户输入的值
    valueSearchMember:'',
    zhilingsetShow:false,
     //间隔时间
     showHealth: false,
     showPositioning: false,
     positioningReportInterval:null,
     healthReportInterval:null,
     project:null,
     immediatelyLocateRadio:"",
     showImmediatelyLocate:false

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //当前登录用户
    let user=	app.globalData.userInfo;
    console.log("user");
    console.log(user);
    this.setData({
      user: user,
      authority:app.globalData.authority
    })
    let targetValue = false;
    user.roles.forEach((role) => {
         // 若已找到目标值，直接返回（提前终止遍历）
          if (targetValue) return;
          const iotWeapp = role.uiAuthOfRole.iot_weapp;
           // 逐层判断属性（支持可选链操作简化代码）
          if (
            iotWeapp &&
            iotWeapp.menu?.manage?.userCard?.wristbandInterval === true
          ) {
            targetValue = true; // 赋值
          }
    })


    if(user.type == 1 || targetValue){
      this.setData({
        showImmediatelyLocate: true
      })
    };

    //客户只查自己的项目
    if(user.departObj[0].type==4){
      this.setData({
        member: user.departObj[0]
      })

      //获取项目数据
      this.getList();
    }else{
      //其他类型先获取一级部门再查下级项目
      this.getMemberList();
    }  
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let member=this.data.member;
    console.log("member");
    console.log(member);
    let param={
     // isAuth:false,
      className:"depart",
      data:{
        selectFields:["id","name","nickName","addressDetail","area","cleanLeader","offMessageUsers","offMessageInterval","healthReportInterval","positioningReportInterval","level"],
        page:{
          page:this.data.page,
          pageSize:10
        },
        sort: {
          id: -1
        },
      }
    }

    if (this.data.searchValue != ""){
      param.data.name = '%'+this.data.searchValue+'%'
    }

    console.log("0000000000")
    console.log(param)
    CommonService.goFindList(param).then(res=>{      
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log('项目列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })

    if(!e.detail.value){
      //刷新列表和页码
      this.refreshListAndPage();
    }
  },
  showPopup(e) {
    console.log("进来了吗");
    console.log(e);
    this.setData({
      zhilingsetShow: true,
      project:e.currentTarget.dataset.project,
      healthReportInterval:e.currentTarget.dataset.project.healthReportInterval,
      positioningReportInterval:e.currentTarget.dataset.project.positioningReportInterval
		})
  },
   //选择定位类型
 onChangeType(event) {
  this.setData({
    type: event.detail,
    disabled: false
  })

  //显示WIFI间隔
  if(event.detail.indexOf('health')!=-1){
    this.setData({
      showHealth: true
    })
  }else{
    this.setData({
      showHealth: false
    })
  }

  //显示GPS间隔
  if(event.detail.indexOf('positioning')!=-1){
    this.setData({
      showPositioning: true
    })
  }else{
    this.setData({
      showPositioning: false
    })
  }
},
  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转添加/编辑
  goToAdd(e){
    let member=this.data.member;
    let id=null;      

    if(e.currentTarget.dataset.detail){
      let detail=e.currentTarget.dataset.detail;
      id=detail.id;      
    }

    let obj={
      id: id,
      companyId: member.id,
      companyName: member.name,
      level:e.currentTarget.dataset.detail.level
    }
    console.log(e);


    wx.navigateTo({
      url: "/pages/departAdd/departAdd?paramObj="+JSON.stringify(obj)
    })
  }, 

  //显示删除确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showDelete: true,
      deleteId:detail.id
		})
  },

  //隐藏删除确认框
  onCloseDelete(){
    this.setData({
			showDelete: false
		})
  },

  //确认删除
  confirmDelete(){
    let param={ 
      className:"depart",
      data:{
        id:this.data.deleteId
      }
    }

    CommonService.goDelete(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        //刷新列表和页码
        this.refreshListAndPage();        
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    }) 
  },

  //显示客户选择框
  onShowMember(){
    this.setData({
			showMember: true
    })
  },

  //隐藏客户选择框
  onCloseMember(){
    this.setData({
			showMember: false
    })
  },

  onChangeImmediatelyLocate(event){
    console.log("22222");
    console.log(event);
    this.setData({
      immediatelyLocateRadio: event.detail,
    });
  },
  //点击立即定位单选框
  onClickImmediatelyLocate(event){
    const { name } = event.currentTarget.dataset;
    console.log("11111");
    console.log(name);
    this.setData({
      immediatelyLocateRadio: name,
    });
  },

  onCloseInstructions(){
    this.setData({
			zhilingsetShow: false
    })
  },
  confirmFormInstructions(e){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...',
      zIndex: 999
    });
    let obj = e.detail.value
     //类型为WIFI
   
    let healthReportInterval=obj.healthReportInterval.trim();
    //是否是数字且在范围内
    if(healthReportInterval){
      if(healthReportInterval>=1 && healthReportInterval<=600){
        obj.healthReportInterval=parseInt(healthReportInterval);
      }else{
        Toast.fail('请输入1至600之间数字');
        return;
      }
    }else{
      Toast.fail('请输入健康间隔时间');
      return;
    }
  

  //类型为GPS
  
    let positioningReportInterval=obj.positioningReportInterval.trim();
    if(positioningReportInterval){
      if(positioningReportInterval>=1 && positioningReportInterval<=600){
        obj.positioningReportInterval=parseInt(positioningReportInterval);
      }else{
        Toast.fail('请输入1至600之间数字');
        return;
      }  
    }else{
      Toast.fail('请输入定位间隔时间');
      return;
    }
  console.log(obj);
  const {project} = this.data;
  console.log("project");
  console.log(project);
  this.sendInstructions(obj,project);
  
  },

    //发送指令
    async sendInstructions(obj,project){

     let flg = true;
     console.log("obj");
     console.log(obj);
     console.log("project");
     console.log(project);

      if (obj.healthReportInterval != project.healthReportInterval){
        console.log("zhilfanhui");
        let healthInstructions = {   
              "url": "/setDeviceConfig/interval",
              "body": {
                  "interval": obj.healthReportInterval,
                  "switch": 1,
                  "type": 1
              },
              "projectId" :project.id
          }
        // let healthInstructions = {
        //       "url":"/setDeviceConfig/interval",
        //       "body":{
        //           "imei":"861265062420135",
        //           "interval": 32,
        //           "switch": 1,
        //           "type": 1
        //       }
        //   }
        console.log("zhilfanhui");
        await  CommonService.batchSendInstruction(healthInstructions).then(res=>{
          console.log("zhilfanhui");    
          console.log(res);
              if(res.data.status != 1){
                flg = false;
              }
          })

      }
      if (obj.positioningReportInterval != project.positioningReportInterval){
        let positioningInstructions = {   
              "url": "/setDeviceConfig/interval",
              "body": {
                  "interval": obj.positioningReportInterval,
                  "switch": 1,
                  "type": 4
              },
              "projectId" :project.id
          }
          await  CommonService.batchSendInstruction(positioningInstructions).then(res1=>{
            console.log("zhilfanhui11111111111");
            console.log(res1);
            if(res1.data.status != 1){
              flg = false;
            }
        })
      }

      console.log(this.data.immediatelyLocateRadio);
      
      //立即定位
      if(this.data.immediatelyLocateRadio == "1"){
        console.log("ksdjfksjdfk");
        let immediatelyLocateInstructions = {
              "url":"/sendDeviceInstructions",
              "body":{
                  "command":128
              },
              "projectId" : project.id
          }
          await  CommonService.batchSendInstruction(immediatelyLocateInstructions).then(res=>{
            console.log(res);
        })
      }

      console.log("flg");
      console.log(flg);

      if (flg){
          //修改部门表
          let params = {
            className:'depart',
            data:{
                  id:project.id,
                  healthReportInterval:obj.healthReportInterval,
                  positioningReportInterval:obj.positioningReportInterval
                }          
          }
          console.log("params");
          console.log(params);
          CommonService.goSave(params).then(res=>{
            console.log(res);
            if (res.statusCode == 200 && res.data.success == true){
              Toast.success('操作成功');  
              this.onCloseInstructions();
              Toast.clear();
            }else{
              Toast.clear();
            }
        })
      }
      Toast.clear();
    
  },

  //确认客户
  onConfirmMember(e){
    this.setData({
      member: e.detail.value.obj
    })
    this.onCloseMember();
    //获取项目数据
    this.refreshListAndPage();
  },

  //获取客户数据
  getMemberList(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        level:1,
        complex:[{
          "or": {
            type:4,
            multiType:4,
          }
        }],
        name:{
          '!=':''
        },
        selectFields:['id','name','companyId','partnerId','fid','level','healthReportInterval','positioningReportInterval']
      }
    }

    //客户名称模糊查询
    if(this.data.valueSearchMember){
      param.data.name='%'+this.data.valueSearchMember+'%'      
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.count){
        let list=res.data.data.result;        
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            obj:list[i]
          }
          arr.push(obj);
        }
        this.setData({ 
          memberList: arr,
          member:list[0]
        })

        //获取项目数据
        this.getList();
      }
    }).catch((error) => {
    })
  },

  //选择客户-搜索
  onChangeMemberName(e){
    this.setData({
      valueSearchMember: e.detail
    })

    //获取客户数据
    this.getMemberList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})